7.4 What and how to control

  1. Motivations
  2. Events and event driven programming
    • In the previous two assignments, you can select the board size and click the button to start the game.
    • In this image, event emitters are HTML elements in the body. For example, when the user clicks an element, the 'click' event is emitted from the element. In another word, the 'click' event is triggered on the element. Then the event handler, which is usually a function and registered for the 'click' event on the element, will be invoked.
    • The question is, when the user can trigger events on HTML elements, which event handlers should be executed? Who provides the event handlers?
    • Before we discuss the above questions, what kind of events do you think you need?
      • Mouse events - click, mouseover, mouseout, ...
      • Key events - keydown, keyup, ...
      • Window events - ...
      • ...
    • Read all in JavaScript Events.
      • Did you do the exercises at the bottom in the above link?
      • List all the common events explained.
      • What can you do with JavaScript and events?
      • Explain how the onclick attribute is used. You have seen many examples.
      • Trial 1: Let's try to display date and time. When a button is clicked, a <p> is updated.


      • Trial 2: Let's try to change the background color to 'LightBlue' when the mouse moves over a <div> box. You need to use the two mouse events, not the CSS hover pseudo class.


    • Read all in JavaScript HTML DOM Events.
      • Did you do the exercises at the bottom in the above link?
      • Can you write the code for the first example?
      • How to register event handlers?
      • What is 'this' in the second example?
      • In the second example, can you add some code so that the button has the original string value when it is clicked again?
      • How to access/control/update HTML elements?
      • On what elements is the 'load' event triggered?
      • What is the 'change' event triggered? What elements trigger this event?
      • On what elements are the 'mouseover', 'mouseout', 'mousedown', 'mouseup' and 'click' events triggered?
      • Trial 3: Let's try to change the HTML content when the element is clicked. You can use 'this'.


    • Can you list all the events that you have studied so far?    click, load, change, mouseover, mouseout, mousedown, mouseup
    • There are three event registration models, as follows.
    • The inline event registration model
      • In this model, The invocation of an event handler is registered as inline event attribute value, and some arguments can be passed.
      • We have used this model so far.
    • The W3C event registration model - Read all in JavaScript HTML DOM EventListener.
      • Can you register multiple event handlers?
      • On what object is the 'resize' event triggered?
      • How to remove an event handler?
      • What are the advantages of using this model?    Multiple event handlers, better readability, easy removal of event handlers, ...
      • Trial 4: Let's try to change the HTML content when the element is clicked. You SHOULD use the W3C event registration model, not the inline model.


      • Trial 4-5: Let's try the above example again. Does it work correctly? What happens?
    • The traditional event registration model.
      • Event properties - onclick, onload, onmouseover, onmouseout, onchange, onresize, ...
      • Syntax: In <script>, elementobject.eventproperty = eventhandler;
      • Here is an example.
        <body>
            <button id='button'>Click Me!</button> <!-- There is no invocation of event handler here. -->
            <h id='demo'></h>
        
            <script>
                function clickme() {
                    document.getElementById('demo').innerHTML = 'Hmmm';
                }
                document.getElementById('button').onclick = clickme;
            </script>
        </body>
        
      • What if the script in the above example is before the button?
      • Trial 5: Let's try to change the HTML content when the element is clicked. In this exercise, you are asked to use the traditional event registration model.


    • The better programming style is ...
      • The better programming style is to keep the JavaScript code in <head>, as follows.
        <head>
            <style>
                ...
            </style>
            <script>
                ...
            </script>
        </head>
        <body>
            ...
        </body>
        
      • But, try this example with runcode.
        <head>
            <script>
                // The W3C model
                function clickme() {
                    document.getElementById('demo').innerHTML = 'Hmmm';
                }
                document.getElementById('button').addEventListener('click', clickme);  // NOT the invocation of an event handler
        
                /* Or the traditional model
                function clickme() {
                    document.getElementById('demo').innerHTML = 'Hmmm';
                }
                document.getElementById('button').onclick = clickme;  // NOT the invocation of an event handler
                */
                /* Or
                document.getElementById('button').onclick = function() {  // Anonymouse function - a function that has no name
                    document.getElementById('demo').innerHTML = 'Hmmm';
                }
                */
            </script>
        </head>
        <body>
            <button id='button'>Click Me!</button> <!-- There is no invocation of event handler here. -->
            <p id='demo'></p>
        </body>
        
      • What is wrong with the above example?
        • <script> is executed before <body>. That is, the element of 'button' is undefined in <script>.
        • What are you supposed to do then?
        • document.getElementById('button').addEventListener(...); should be executed after <body> is completed loaded.
        • Now the question is how do you know whether <body> is completed loaded? Any related event?
      • Try this example with runcode again.
        <head>
            <script>
                function clickme() {
                        document.getElementById('demo').innerHTML = 'Hmmm';
                }
                function start() {
                    document.getElementById('button').addEventListener('click', clickme);  // NOT the invocation of an event handler
                }
                window.addEventListener('load', start);  // This event is triggered when the <body> is completely loaded.
                                                         // The second argument is NOT the invocation of an event handler.
                /* OR
                window.addEventListener('???', ???() {
                    document.getElementById('button').addEventListener('click', clickme);
                }); 
                */
            </script>
        </head>
        <body>
            <button id='button'>Click Me!</button> <!-- There is no invocation of event handler here. -->
            <p id='demo'></p>
        </body>
        
    • Can you rewrite all the examples in JavaScript HTML DOM EventListener, so that you can use the above better programming style?
  3. HTML elements for user interaction, and events
    • The button element - Read all in HTML <button> Tag.
      • The attributes - disabled, type, value (not the content between the start and the end tags), ...
      • How to make a button disabled/enabled?
      • Trial 6: Let's try to write the code for the above example.
    • The input, label and form elements - Read all in HTML Forms.
      • The type attribute
        • text
        • submit
        • password
        • radio
        • checkbox
        • number
        • search
        • ...
      • The value attribute
      • Other attributes - name, checked, disabled, autofocus, ...
      • Here is an example. How are the labels 'Password' and 'Size' different from others? Please study the code carefully.
        Username:

        Car: VW Hyundai
        Course: 2680 3540 4620 4680 4910

      • The source code of the above example is
        Username: <input type='text' value='Wow!'><br>
        
        <label for='pswd'>Password:</label> <input id='pswd' type='password' style='width:200px' autofocus><br>
        
        Car: <input type='radio' name='car' value='VW'>VW
        <input is='ford' type='radio' name='car' value='Ford'><label for='ford'>Ford</label>
        <input type='radio' name='car' value='Hyundai' checked>Hyundai<br>
        
        Course: <input type='checkbox' name='course' value='2680' checked>2680
        <input type='checkbox' name='course' value='3540' checked>3540
        <input type='checkbox' name='course' value='4620'>4620
        <input type='checkbox' name='course' value='4680'>4680
        <input type='checkbox' name='course' value='4910'>4910<br>
        
        <label for='sz'>Size:</label> 
        <input id='sz' type='number' min=2 max=10 value='3'><br>
        
        <input type='submit' value='Submit'>
        
      • How to make the input box larger?
      • How to connect a label to an input?
      • What attribute is used to group radio buttons or check boxes?
      • How are radio type and checkbox type different?
    • The select element - Read all in HTML <select> Tag.
      • The attributes - name, value, selected, multiple, disabled, ...
      • Here are examples. Find the difference between the two select examples.
        Car (single selection): Car (multiple selection):     
      • Which attribute is used with select for multiple selection?    multiple
    • The textarea element - Read all in HTML <textarea> Tag.
      • The attributes - name, value, rows, cols, disabled, ...
    • The datalist element - Read all in HTML <datalist> Tag.
      • The 'list' attribute in the input element
      • The 'input' event in the input element having a datalist - This event is triggered as an option is selected, or a key is up.
    • The form element - Read all in HTML Forms.
      • The attributes - action, method, target, ...
      • When do you usually use the forms?
  4. The Event object
    • Here is an example how to use the Event object. From the Event object, we can obtain additional information, such as mouse coordinates and key values.
      document.getElementById('control').addEventListener('click', eh);
      function eh(event) {  // event is an Event object. The browser invokes this function with the Event object.
          event.target.innerHTML = 'Hmmm';  // target: the element object on which this event is triggered.
      }
      
    • List of events - Read all in HTML DOM Events.
    • How to get the key value when a key is pressed?    eventObj.key
    • How to get the position of the mouse pointer?    eventObj.clientX, event.clientY
    • Trial 7: Let's try to capture the mouse position. Which Event properties do you need to use? You are asked to use the W3C event registration model.


    • Trial 8: Let's try to capture the window size. What event do you need to use? You can use innerWidth and innerHeight properties in the window object.


    • How to get the id of the event target object?    eventObj.target.id
  5. Timer
    • The window object supports many useful features. One of them is timer.
    • There are two types of timer - one time timer and repeating timer.
    • One time timer - Read all in Window setTimeout() Method.
      • How to clear the timer? clearTimeout(timerid)
    • Repeating timer - Read all in Window setInterval() Method.
      • How to clear the timer? clearInterval(timerid)
    • Can you display a timer on the n-puzzle game, that displays the elapsed time? Let's try now.    
      <script>
          ??? count;
          function start() {
              document.???('start_button').??? (???, function() {
                  count = ???;
                  window.setInterval(function() {
                      count???;
                      ???.getElementById('seconds').??? = count;
                  },???);  // Every 1 second
              };
          }
          ???.???(???, start);  // When <body> is completely loaded.
      </script>
      
      <body>
          <button id='start_button'>Start the game</button><br>
          <p>Elapsed time: <span id='seconds></span></p>
      </body>
      
    • Trial 9: Let's try to make timer. The timer is invoked every second. Which type timer do you need to use?


    • Trial 10: Let's try to make a wakeup call. You will be called after 10 seconds. Which type timer do you need to use?
      Let's use .setTimeout().


    • Trial 11: Let's try to make a wakeup call. You will be called if there is no activity for 10 seconds. What activity?
      Let's use .setTimeout() and two events - mousemove and keydown.


  6. Document Object Model (DOM)
    • The HTML DOM is a data structure that includes everything in a web document as a node (a name in the DOM data structure). An object will be created in JS for each node.
    • Read all in The HTML DOM Document Object.
      • What is the document object?
      • What methods in the document object have you used?    write(), getElementById(), addEventListener()
      • Some interesting properties - body, title, URL, ...
    • What is the general procedure to control HTML and CSS with JS?    Event -> Obtain HTML/CSS objects. --> Update or use their properties and methods.
    • How to get elements by tag name? Read all in HTML DOM getElementsByTagName() Method.
    • Trial 12: Let's try to change the background color of all the <p> elements.


    • How to get elements by class name? Read all in HTML DOM getElementsByClassName() Method.
    • How to get elements by CSS selector? Read all in HTML DOM querySelectorAll() Method.
    • Trial 13: Let's try to change the background color of all the <p> elements that belong to class 'tr13'.


    • How to control attributes of an element?    elementobj.attributename, elementobj.getAttribute(name), elementobj.setAttribute(name, value)
    • How to control CSS styles (i.e., CSS properties) of an element?    elementobj.style.csspropertyname, elementobj.style.getProperty(name), elementobj.style.setProperty(name, value)
  7. Browser Object Model (BOM)
    • The window object represents an open window in a browser. This object supports many useful properties and methods.
    • Read all in The Window Object.
      • How to get the window size?    window.innerHeight, window.innerWidth
      • List the window properties and methods that you have used.    document, alert(), setInterval(), setTimeout()
      • What kind of events are triggered on window?    load, resize
    • There are other BOM objects - Navigator, Screen, History, Location.
  8. Dynamic style

  9. Learning outcomes